import type { LoginResult } from '@/types/user'
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { getUserPermission, getEnterpriseDetail, getIndexInfo, findUserInfo } from '@/api/common'

// 定义 Store
export const userStore = defineStore(
  'userInfoStore',
  () => {
    // 用户信息
    const profile = ref<LoginResult>()
    const permissons = ref<string[]>([])
    const permissons_need_refresh = ref(true)
    // 商户配置
    const enterpriseDetail = ref({})
    // 首页配置
    const indexInfo = ref({})
    // 员工信息
    const staffInfo = ref<{
      staffId?: string
      realname?: string
    }>({})

    // 保存用户信息，登录时使用
    const setProfile = (val: LoginResult) => {
      profile.value = val
    }

    // 清理用户信息，退出时使用
    const clearProfile = () => {
      profile.value = undefined
      // 清空商户信息
      enterpriseDetail.value = {}
    }

    // 设置用户资源权限
    const setStaffInfo = () => {
      console.log('🐳 ~ 设置用户员工信息 ~ findUserInfo')
      findUserInfo({}).then((res) => {
        const data: any = res.result
        staffInfo.value = {
          staffId: data.employeeId,
          realname: data.realname,
        }
      })
    }

    // 设置用户资源权限
    const setUserPermission = () => {
      return new Promise((resolve) => {
        getUserPermission().then((res: any) => {
          console.log('🐳 ~ 设置用户资源权限 ~ getUserPermission')
          if (res.code == '200') {
            permissons.value = res.result.map((it: any) => it.key)
          }
          resolve('ok')
        })
      })
    }

    // 获取商户信息
    const setEpDetail = (isCache = true) => {
      return new Promise((resolve) => {
        if (enterpriseDetail.value && Object.keys(enterpriseDetail.value).length > 0 && isCache) {
          resolve(enterpriseDetail.value)
        } else {
          getEnterpriseDetail().then((res: any) => {
            if (res.code == 200) {
              const result = res.result
              enterpriseDetail.value = result
              resolve(result)
            }
          })
        }
      })
    }

    // 保存用户信息，登录时使用
    const setIndexInfo = () => {
      getIndexInfo().then((res: any) => {
        if (res.code == 200) {
          const result = res.result
          indexInfo.value = result
        }
      })
      // if (permissons_need_refresh.value) {
      //   permissons_need_refresh.value = false
      // }
      // 进入首页时判断是否需要，刷新权限，热更新后需刷新权限
      setUserPermission()
      // 获取首页获取用户员工信息
      setStaffInfo()
    }

    // 长短租业务配置
    const epServiceTypes = computed(() => {
      return enterpriseDetail.value.userServiceTypes
    })
    // 长短租业务配置是否包含短租
    const epServiceIncludeShortOrder = computed(() => {
      const serviceTypes = epServiceTypes.value || []
      return serviceTypes.includes(1)
    })
    // 长短租业务配置是否包含长租
    const epServiceIncludeLongOrder = computed(() => {
      const serviceTypes = epServiceTypes.value || []
      return serviceTypes.includes(2)
    })
    // 渠道订单同步开关
    const epChannelOrderSync = computed(() => {
      return enterpriseDetail.value.channelOrderSync
    })
    // 渠道订单维护方式
    const epChannelOrderMaintenance = computed(() => {
      return enterpriseDetail.value.channelOrderMaintenance
    })
    // 支付宝免押码是否开启
    const epAlipaySwitch = computed(() => {
      return enterpriseDetail.value.alipaySwitch
    })
    // ocr识别是否开启
    const epOcrSwitch = computed(() => {
      return enterpriseDetail.value?.config?.ocrSwitch
    })

    // 鉴权
    const v_auth = (key: string) => {
      return permissons.value.includes(key)
    }

    // 记得 return
    return {
      profile,
      permissons,
      permissons_need_refresh,
      staffInfo,
      setProfile,
      clearProfile,
      setUserPermission,
      setStaffInfo,
      v_auth,

      indexInfo,
      setIndexInfo,

      setEpDetail,
      enterpriseDetail,
      epServiceTypes,
      epServiceIncludeShortOrder,
      epServiceIncludeLongOrder,
      epChannelOrderSync,
      epChannelOrderMaintenance,
      epAlipaySwitch,
      epOcrSwitch,
    }
  },
  {
    // 网页端配置
    // persist: true,
    // 小程序端配置
    persist: {
      storage: {
        getItem(key) {
          return uni.getStorageSync(key)
        },
        setItem(key, value) {
          uni.setStorageSync(key, value)
        },
      },
    },
  },
)
